package cn.lblbc.appstore.module.download

import android.util.Log
import cn.lblbc.appstore.utils.AppUtils.getVersionCode

object StatusManager {
    private var listeners = mutableMapOf<String, MutableList<StatusListener>>()
    private var statusMap = mutableMapOf<String, StatusInfo>()

    fun notifyLocalChanges(key: String, appInfo: SimpleAppInfo?) {
        val statusInfo = findStatusByKey(key)
        statusInfo.localAppInfo = appInfo
        notify(key, statusInfo)
    }

    fun notifyServerChanges(key: String, appInfo: SimpleAppInfo) {
        val statusInfo = findStatusByKey(key)
        statusInfo.serverAppInfo = appInfo
        notify(key, statusInfo)
    }

    fun notifyDownloadChanges(key: String, downloadFileInfo: DownloadFileInfo) {
        val statusInfo = findStatusByKey(key)
        statusInfo.downloadFileInfo = downloadFileInfo
        notify(key, statusInfo)
    }

    fun notifyInstallChanges(key: String, isInstalling: Boolean) {
        val statusInfo = findStatusByKey(key)
        statusInfo.isInstalling = isInstalling
        notify(key, statusInfo)
    }

    private fun notify(key: String, statusInfo: StatusInfo) {
        val list = findListenerByKey(key)
        list.forEach { it.onUpdate(statusInfo) }
    }

    fun register(appPackageName: String, statusListener: StatusListener) {
        val list = findListenerByKey(appPackageName)
        listeners[appPackageName] = list
        list.add(statusListener)
        checkLocalAppStatus(appPackageName)
    }

    fun checkLocalAppStatus(appPackageName: String) {
        val versionCode = getVersionCode(appPackageName)
        if (versionCode != -1L) {
            notifyLocalChanges(appPackageName, SimpleAppInfo(versionCode))
        } else {
            notifyLocalChanges(appPackageName, null)
        }
    }

    fun unregister(key: String, statusListener: StatusListener) {
        val list = findListenerByKey(key)
        list.remove(statusListener)
    }

    private fun findListenerByKey(key: String): MutableList<StatusListener> {
        return if (listeners.containsKey(key)) {
            listeners[key]!!
        } else {
            mutableListOf()
        }
    }

    private fun findStatusByKey(key: String): StatusInfo {
        if (!statusMap.containsKey(key)) {
            val statusInfo = StatusInfo()
            statusMap[key] = statusInfo
        }
        return statusMap[key]!!
    }

}